<?php

App::import('Vendor', 'Uploader.Uploader');
App::import('Model', 'Account');
App::import('Model', 'Post');
App::import('Model', 'ArchivedTweet');

class Tweet extends AppModel {

    var $primaryKey = 'postID';

    /**
     * 
     * @author Nada
     * A function taking the account ID as an input and returns the last acount last tweet
     * @param string $accID
     * @return Tweet 
     */
    function getLastTweet($accID = NULL) {


        $accExists = $this->query("Select * from accounts where accounts.accID = " . $accID);
        if ($accExists) {

            if ($accID != NULL) {
                $res = $this->query("Select * from tweets, posts where
                                    posts.postID = tweets.postID and
                                    posts.accID = " . $accID . "
                                    ORDER BY posts.time DESC LIMIT 1");
            }

            if ($res != NULL) {

                return $res;
            } else {

                return null;
            }
        } else {
            return 'no such account';
        }
    }

    /**
     * @author Nada
     * @param int $tweetID
     * @return  Tweet
     * the function returns a tweet given its ID
     */
    function getTweet($tweetID) {
//return $this->query("Select * from tweets, posts where posts.postID = tweets.postID and tweets.postID =".$tweetID);
//return $this->query("Select * from posts where posts.postID =".$tweetID);
        $options['joins'] = array(
            array('table' => 'posts',
                'alias' => 'post',
                'type' => 'inner',
                'fields' => 'tweet.postID',
                'conditions' => array(
                    'Post.postID = Tweet.postID',
                )
            )
        );
        $options['conditions'] = array('Post.postID' => $tweetID);
        $options['fields'] = array('*');

        $return = $this->find('all', $options);
//print_r($return);
        return $return;
    }

    public function getduplicate($text, $accuntid) {
        $options['joins'] = array(
            array('table' => 'posts',
                'alias' => 'Post',
                'type' => 'inner',
                'conditions' => array(
                    'Post.postID = Tweet.postID',
                )
            )
        );
        $options['conditions'] = array('AND' => array(
                "post.accID" => $accuntid, "Post.text" => $text, array("Post.time BETWEEN ? AND ?" => array(date('Y-m-d H:i:s', strtotime("-1 days")), date('Y-m-d H:i:s')))));
        $tem = $this->find('all', $options);
        return $tem;
    }

    /*
     * Description of "getFav"
     * @param  "postID"
     *
     * description of the function:
     * This function in the model is dedicated to get from the tweets table
     * the number of favourites of a certain tweet passed by its postID and
     * this is piece of information is placed in columb 'favourites' in the table
     * @author "Mo'men el Sawy"
     */

    function getFav($primaryKey) {
        $count = $this->find('count');
        if ($count != 0) {

            return $this->read('Favourites', $primaryKey);
        } else {
            return 0;     //The Database is currently empty
        }
    }

    /*
     * Description of "getNumRetweet"
     * @param  "postID"
     *
     * description of the function:
     * This function in this model is dedicated to get from the tweets table
     * the number of Retweets of a certain tweet passed by its postID and
     * this is piece of information is placed in columb 'retweets' in the table
     * @author "Mo'men el Sawy"
     */

    function getNumRetweet($primaryKey) {

        $count = $this->find('count');
        if ($count != 0) {

            return $this->read('retweets', $primaryKey);
        } else {
            return 0;     //the Database is currently empty
        }
    }

    /*
     * Description of "post_to_twitter"
     *
     * the function takes a post that is a tweet and send it to twitter to be posted there
     *  @param  Future Tweet $arraydata 
     *  @return boolean
     * 
     * @author "Menah ElBastawisy"

     */

     public function post_to_twitter($arraydata) {//edited by Menah ElBastawisy
        $tmpAccount = new Account();
        $Post = new Post();
        $status = ( $tmpAccount->connectionRequest($arraydata['accID'])->Post('statuses/update', array('status' => $arraydata['tweetText'], 'in_reply_to_status_id' => $arraydata['reply_to'])));
        $tweet = (array) $status;
        $Post->set(array('postID' => $tweet['id_str'], 'accID' => $arraydata['accID'], 'userID' => $arraydata['userID'], 'text' => $arraydata['tweetText'], 'time' => $arraydata['sub_time']));
        $Post->save();
        $this->set(array('postID' => $tweet['id_str'], 'retweets' => 0, 'favorites' => 0, 'isMention' => 0, 'restored' => 0, 'restoreDate' => NULL, 'subTime' => $arraydata['sub_time'], 'restoredBY' => NULL, 'eventID' => $arraydata['eventID'], 'tweetInterval' => NULL, 'replyTo' => $arraydata['reply_to']));
        $this->save();
        
        return true;
    }

    /*
     * 
     * Description:
     *
     * the function takes the uploaded photo and text and post it to twitter
     * @param $data
     * @return boolean
     * @author "Menah ElBastawisy"
     */

    public function upload($data=NULL) {
        $this->Uploader = new Uploader();
        $this->Uploader = new Uploader(array('tempDir' => TMP));
        if ($dataimag = $this->Uploader->upload($data['Tweet']['fileName'])) {
            $tmpAccount = new Account();
            $image = $data['Tweet']['fileName'];
            $code = $tmpAccount->connectionRequest('262320739')->POST('https://upload.twitter.com/1/statuses/update_with_media.json', array('media[]' => $image, 'status' => $data['Tweet']['text']));
            $arrayimage = (array) $code;
            print_r($arrayimage);
            if ($arrayimage['error']) {
                echo 'the tweet was not posted';
            }
            return true;
            // Upload successful, do whatever 
        }
    }

    /**
     * Description of function "deleteT"
     * @param string $postID
     * @param string $currUser
     * @return boolean
     * 
     * Description:
     * A function taking the post ID and the user who will delete the tweet
     * as an input and deletes it(move tweet's data to archived_tweets table)
     * @author "Omar Elshal"
     */
    public function deleteT($postID, $currUser) {

        $options['joins'] = array(
            array('table' => 'posts',
                'alias' => 'Post',
                'type' => 'INNER',
                'order' => array('Tweet.postID' => 'desc'),
                'conditions' => array('Tweet.postID = Post.postID', 'Post.postID' => $postID)
                ));


        $result = $this->find('all', $options);
        $counter = $this->find('count', $options);

        print_r($result);
        if ($counter != 0) {

            $at = new ArchivedTweet;
            $at->set(array(
                'postID' => $result[0]['Tweet']['postID'],
                'retweets' => $result[0]['Tweet']['retweets'],
                'favourites' => $result[0]['Tweet']['favourites'],
                'isMention' => $result[0]['Tweet']['isMention'],
                'subTime' => $result[0]['Tweet']['subTime'],
                'deletedBy' => $currUser,
                'eventID' => $result[0]['Tweet']['eventID'],
                'tweetInterval' => $result[0]['Tweet']['tweetInterval']
            ));


            $at->save();


            if ($this->delete($postID)) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * Unfavorites a tweet
     *
     * @access: public
     * @param: $accountID, the id of the authorized account
     * @param: $tweetID, the id of the tweet to unfavorite
     *
     * @author "Hussein Abo El Seoud"
     */
    public function unfavorite($accountID, $tweetID) {
        $tempAccount = new Account();
        $status = $tempAccount->connectionRequest($accountID)->delete('favorites/destroy/' . $tweetID);
        $post = new Post();
        if (!$post->isUnique("postID", $tweetID)) {
            //update the database
            $this->save(array('postID' => $tweetID, 'favorited_by_us' => FALSE), false);
        }
    }

    /*
     * Description of "favorite"
     * @param  "accountid" ,"postid" , "home"
     *
     * This function Updates the database after making sure that twitter favourited the tweet.
     * @author "Sherif Ismail"
     */

    public function favorite($accountid, $postid, $home) {
        $Account = new Account();
        $status = ( $Account->connectionRequest($accountid)->Post('favorites/create/' . $postid));
        $check = (array) $status;
        if (array_key_exists('error',$check)) {
            return false;
        }
        if ($home == '0') {
            $this->read(null, $postid);
            $this->set('favorited_by_us', 1);
            $this->save();
        }
        return true;
    }

    /**
     * Retweets a tweet
     *
     * @access: public
     * @param: $accountID, the id of the authorized account
     * @param: $tweetID, the id of the tweet to be retweeted
     *
     * @author "Menah ELBastawisy"
     */
    public function retweetTweet($accountID, $tweetID,$home) {
        $tempAccount = new Account();
        $status = $tempAccount->connectionRequest($accountID)->post('statuses/retweet/' . $tweetID);
        $retweet = (array) $status;
        if (($retweet == NULL)||($retweet['error'])){
            return false;
        } else {
            if($home==0){
            $tweet = array('postID' => $tweetID, 'retweeted_by_us' => TRUE);
            $this->save($tweet);
            $retweetT = (array) $retweet['retweeted_status'];
            $user = (array) $retweetT['user'];
            $mysql_format = date("Y-m-d H:i:s", strtotime($retweet['created_at']));
            $this->query("insert into twitteraccounts_retweet_tweets values ('" . $user['id_str'] . "','" . $tweetID . "','" . $mysql_format . "','" . $retweet['id_str'] . "')");
            return TRUE;
            }else{
                return TRUE;
            }
        }
    }

    /**
     * Undo retweet of a tweet
     *
     * @access: public
     * @param: $accountID, the id of the authorized account
     * @param: $tweetID, the id of the tweet to be unretweeted
     *
     * @author "Menah ELBastawisy"
     */
    public function unRetweet($accountID, $tweetID) {
        $tempAccount = new Account();
        $new = $this->query("select twitteraccounts_retweet_tweets.new_id from twitteraccounts_retweet_tweets where twitteraccounts_retweet_tweets.postID ='" . $tweetID . "' ");
        if ($new != NULL) {

            $newTweet = $new['0']['twitteraccounts_retweet_tweets']['new_id'];
            $status = $tempAccount->connectionRequest($accountID)->post('statuses/destroy/' . $newTweet);
            $tweet = array('postID' => $tweetID, 'retweeted_by_us' => false);
            $this->save($tweet);
            $this->query("delete from twitteraccounts_retweet_tweets where  twitteraccounts_retweet_tweets.postID ='" . $tweetID . "'  ");
            return TRUE;
        } else {
            return false;
        }
    }

    /**
     * Description of checkemptytext
     *
     * @param $reply,$text
     *
     * checks if text is empty
     *
     * @author Sherif Ismail
     */
    function checkReplyspaces($text, $reply) {
        for ($i = strlen($reply); $i < strlen($text); $i++) {
            if (substr($text, $i, 1) != ' ') {
                return true;
            }
        }
        return false;
    }

    /**
     * Description of overlength
     *
     * @param $text
     *
     * checks if text exceede the 140 chars but if it contains a link it returns true.
     *
     * @author Sherif Ismail
     */
    function overlength($text) {
        if (strlen($text) > 140) {
            $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
            $arraytext = explode(' ', $text);
            foreach ($arraytext as $link) {
                if (preg_match($reg_exUrl, $link, $url)) {
                    return true;
                }
            }
            return false;
        } else {
            return true;
        }
    }
     public function deleteOne($postID){
        return $this->delete($postID);
    }


}